import { createSlice, PayloadAction } from '@reduxjs/toolkit';
export const TaskId = 'TaskId';
export type ImageType = {
  action: 'IMAGINE' | 'UPSCALE';
  task_id: string;
  status: 0 | 1 | 2 | 3 | 4; //0(未开始),3（处理中）,2（失败）,1（成功），4（压缩）
  progress: string;
  fail_reason: string;
  image_url: string;
  image_compress_url: string;
  prompt: string;
};
const initialState = {
  image: null as null | ImageType,
  task_id: localStorage.getItem(TaskId) || '',
  prompt: '',
  taskMap: {} as Record<string, Array<undefined | 'pending' | 'loaded'>>,
};

const image = createSlice({
  name: 'image',
  initialState,
  reducers: {
    setState(state, action: PayloadAction<Partial<imageState>>) {
      Object.assign(state, action.payload);
    },
    setTaskNum(
      state,
      action: PayloadAction<{
        number: number;
        stat: undefined | 'pending' | 'loaded';
      }>
    ) {
      const taskId = state.task_id;
      if (!state.taskMap[taskId]) {
        state.taskMap[taskId] = [];
      }
      state.taskMap[taskId][action.payload.number] = action.payload.stat;
      state.taskMap[taskId] = state.taskMap[taskId].slice();
    },
  },
  extraReducers: () => {},
});

export type imageState = typeof initialState;
export const imageReducer = image.reducer;
export const imageActions = image.actions;
export default image;
